package io.xxx;

import java.util.Arrays;

public class PlusOne {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(plusOne(new int[]{1, 2, 3})));
        System.out.println(Arrays.toString(plusOne(new int[]{4, 3, 2, 1})));
        System.out.println(Arrays.toString(plusOne(new int[]{0})));
    }

    public static int[] plusOne(int[] digits) {
        int carry = 0;
        int n = digits.length;
        while (n-- > 0) {
            int digit = digits[n] + carry;
            if (n == digits.length - 1) {
                digit++;
            }
            digits[n] = digit % 10;
            carry = digit / 10;
        }

        int[] rev = new int[digits.length + carry];
        for (int i = digits.length - 1, j = rev.length - 1; i >= 0; i--, j--) {
            rev[i] = digits[i];
        }
        if (carry > 0) {
            rev[0] = carry;
        }
        return rev;
    }
}
